package controller

import (
	"encoding/json"
	"gitee.com/zhoulvvv/my_go_gateway/dto"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"gitee.com/zhoulvvv/my_go_gateway/services"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"time"
)

type AdminLoginController struct {
}

func RegisterAdminLoginController(group *gin.RouterGroup) {
	adminLogin := &AdminLoginController{}
	group.POST("/login", adminLogin.AdminLogin)
	group.GET("/logout", adminLogin.AdminLoginOut)
}

// AdminLogin godoc
// @Summary 用户登录
// @Description 用户登录
// @Tags 用户接口
// @ID /admin_login/login
// @Accept  json
// @Produce  json
// @Param body body dto.AdminLoginInput true "body"
// @Success 200 {object} middleware.Response{data=dto.AdminLoginOutput} "success"
// @Router /admin_login/login [post]
func (adminLogin *AdminLoginController) AdminLogin(c *gin.Context) {
	params := &dto.AdminLoginInput{}
	// 校验参数并把参数绑定到params中
	if err := params.BindValidaParam(c); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	// 登录校验
	adminService := &services.AdminLoginService{}
	admin, err := adminService.LoginCheck(c, params)
	if err != nil {
		middleware.ResponseError(c, 2001, err)
		return
	}
	// 设置session
	adminSess := &dto.AdminSessionInfo{
		ID:        admin.Id,
		UserName:  admin.UserName,
		LoginTime: time.Now(),
	}
	sessBits, err := json.Marshal(adminSess)
	if err != nil {
		middleware.ResponseError(c, 2002, err)
		return
	}
	sess := sessions.Default(c)
	sess.Set(public.AdminSessionInfoKey, string(sessBits))
	sess.Save()
	// 生成Token
	out := &dto.AdminLoginOutput{Token: params.UserName}
	middleware.ResponseSuccess(c, out)
}

// AdminLoginOut godoc
// @Summary 用户退出登录
// @Description 用户退出登录
// @Tags 用户接口
// @ID /admin_login/logout
// @Accept  json
// @Produce  json
// @Success 200 {object} middleware.Response{data=string} "success"
// @Router /admin_login/logout [get]
func (adminLogin *AdminLoginController) AdminLoginOut(c *gin.Context) {
	sess := sessions.Default(c)
	sess.Delete(public.AdminSessionInfoKey)
	sess.Save()
	middleware.ResponseSuccess(c, "成功退出登录")
}
